#
#===============================================================================
#
#         FILE:  FML.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/14/2010 11:50:17 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::FML;

use LWP::UserAgent;
use XML::Simple;

sub register {
    my $self = shift;

    return ('cmd' => 'fml', 'pat' => '^(!fml\s*(.*))|(http:\/\/(?:www.)fmylife.com\/(?:[a-z]+\/)?([0-9]+))');
}

sub help {
    my $self = shift;

    return (
	    'Get random, specific, or latest FML in a category',
	    '!fml 12345678 to get return a specific result',
	    '!fml to get a random result',
	    '!fml <category> to get the latest result from that category',
	    'Available categories are love, money, kids, work, health, intimacy, and miscellaneous'
	   );
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    my $arg;
    if ($msgtxt =~ /^!fml\s*(.*)/) {
        $arg = $1;
    } elsif ($msgtxt =~ /http:\/\/(?:www.)fmylife.com\/(?:[a-z]+\/)?([0-9]+)/) {
	$arg = $1;
    }
# maybe use WWW::FMyLife if they add options to get a specific id or category,
# for now, we'll do it the this way. hey, at least we have an API now.
    my $ua = LWP::UserAgent->new('agent'=>'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1)');
    my $url = 'http://api.betacie.com/view/';
    if( $arg =~ /^[\d]+$/ ) {
    	$url .= "$arg/nocomment";
    }
    elsif( $arg =~ /last|love|money|kids|work|health|intimacy|miscellaneous/ ) {
	$url .= "$arg/1";
    }
    else {
	$url .= "random";
    }
    my $res = $ua->post($url, {'key' => '4bb345e8eb80d', 'language' => 'en'});
    my $xs = XML::Simple->new;
    my $xml = $xs->XMLin($res->decoded_content);
    my $item;

    if( $xml->{'items'}{'item'}{'id'} ) {
	$item = $xml->{'items'}{'item'};
    }
    else {
	my ($id) = keys %{$xml->{'items'}{'item'}};
	$item = $xml->{'items'}{'item'}{$id};
    }
    $kernel->post($sender => privmsg => $target => $item->{'text'});
}

1;
